extends Node

var ghost_node = preload("res://scenes/entities/player/ghost.tscn")
var skill_pool = preload("res://data/skill_pool/skill_pool.tres")
var current_skills = []

## 获取技能
func get_random_skill(level: int = 1) -> String:
	var skill: PandoraEntity = skill_pool.get_random_unit()
	return add_skill(skill, level)

## 添加技能以及对应的等级
func add_skill(skill: PandoraEntity, level):
	var skill_name = skill.get_string("name")
	for current_skill: PandoraEntity in current_skills:
		# 检查当前技能列表中是否已存在该技能
		if current_skill.get_string("name") == skill_name:
			# 技能已存在，升级技能等级
			var current_level = current_skill.get_integer("level")
			# 先移除旧等级的效果（如果是被动技能）
			if current_skill.get_integer("need_mp") < 0:
				remove_skill_func(skill_name, current_level)
			# 升级技能等级
			current_skill.set_integer("level", current_level + level)
			update_skill_info(current_skill, skill_name, current_skill.get_integer("level"))
			# 应用新等级的效果（如果是被动技能）
			if current_skill.get_integer("need_mp") < 0:
				get_skill_func(skill_name, current_skill.get_integer("level")).callv([])
			EventBus.push_event("player_skill_change", [current_skills])
			print("技能已存在，升级技能: " + skill_name + " 等级: " + str(current_skill.get_integer("level")))
			return skill_name
	# 如果没有该技能，且技能数量未满6个，则添加新技能
	if current_skills.size() < 6:
		skill.set_integer("level", level)
		# 这里可以根据需要设置need_mp等属性
		current_skills.push_back(skill)
		update_skill_info(skill, skill_name, level)
		if skill.get_integer("need_mp") < 0:
			get_skill_func(skill_name, level).callv([])
		EventBus.push_event("player_skill_change", [current_skills])
		print("添加新技能: " + skill_name + " 当前技能数量: " + str(current_skills.size()))
		return skill_name
	else:
		# 技能数量已达上限，随机升级一个已有技能
		var random_skill = current_skills.pick_random()
		var current_level = random_skill.get_integer("level")
		var skill_name_to_upgrade = random_skill.get_string("name")
		# 先移除旧等级的效果（如果是被动技能）
		if random_skill.get_integer("need_mp") < 0:
			remove_skill_func(skill_name_to_upgrade, current_level)
		# 升级技能等级
		random_skill.set_integer("level", current_level + level)
		update_skill_info(random_skill, skill_name_to_upgrade, random_skill.get_integer("level"))
		# 应用新等级的效果（如果是被动技能）
		if random_skill.get_integer("need_mp") < 0:
			get_skill_func(skill_name_to_upgrade, random_skill.get_integer("level")).callv([])
		print("技能数量已达上限，随机升级技能: " + skill_name_to_upgrade + " 等级: " + str(random_skill.get_integer("level")))
		return skill_name_to_upgrade

func remove_skill_func(skill_name, level):
	match skill_name:
		"大肉": 
			Utils.set_player_stats_value("current_hp", -10 * level)
			Utils.set_player_stats_value("max_hp", -10 * level)
		"魔法之书":
			Utils.set_player_stats_value("current_mp", -10 * level)
			Utils.set_player_stats_value("max_mp", -10 * level)
		"水之庇护":
			# 水之庇护是被动技能，直接应用属性加成
			var move_speed_bonus = 10 * level
			var attack_speed_bonus = 10 * level

			# 先移除之前的加成（如果有的话）
			Utils.set_player_stats_value("additional_move_speed", -move_speed_bonus)
			Utils.set_player_stats_value("additional_attack_speed", -attack_speed_bonus)
## 根据技能名获取功能效果
func get_skill_func(skill_name, level) -> Callable:
	match skill_name:
		"攻击提升":
			return (
				func (): 
					var damage_bonus = Utils.player.player_stats.get_float("base_damage") * (level * 0.1)
					var buff = BuffFactory.create_attack_buff(damage_bonus, 10.0)
					Utils.player.buff_manager.add_buff(buff, Utils.player)
					Utils.show_string_label_c("攻击提升", Utils.player, Color.CYAN)
					# 改变剑的颜色
					_change_sword_color(Color.ORANGE, 10.0)
			)
		"大肉":
			return (
				func (): 
					Utils.set_player_stats_value("current_hp", 10 * level)
					Utils.set_player_stats_value("max_hp", 10 * level)
			)
		"冲刺":
			return (
				func (): 
					Utils.set_player_stats_value("move_speed", 1000)
					print("使用冲刺技能")
					for i in range(5 + level + 1):
						await get_tree().create_timer(0.05).timeout
						var ghost: Ghost = ghost_node.instantiate()
						ghost.set_property(Utils.player.global_position, Utils.player.visuals, Utils.player.scale)
						add_child(ghost)
						remove_script(ghost)
					Utils.set_player_stats_value("move_speed", -1000)
			)
		"魔法之书":
			return (
				func ():
					Utils.set_player_stats_value("current_mp", 10 * level)
					Utils.set_player_stats_value("max_mp", 10 * level)
			)
		"灼烧":
			return (
				func ():
					var firing = BuffFactory.create_custom_buff("灼烧", -1, 1)
					Utils.player.buff_manager.add_buff(firing)
			)
		"治疗术":
			return (
				func (): 
					var heal_amount = 5 * level + Utils.get_player_stats_value("max_mp")
					var current_hp = Utils.get_player_stats_value("current_hp")
					var max_hp = Utils.get_player_stats_value("max_hp")
					var additonal_max_hp = Utils.get_player_stats_value("additional_max_hp")
					# 计算实际治疗量（不能超过最大生命值）
					var actual_heal = min(heal_amount, max_hp + additonal_max_hp - current_hp)
					if actual_heal > 0:
						Utils.set_player_stats_value("current_hp", actual_heal)
						Utils.show_string_label_c("+" + str(actual_heal), Utils.player, Color.GREEN)
						print("治疗术恢复生命值: " + str(actual_heal))
					else:
						Utils.show_string_label_c("生命值已满", Utils.player, Color.YELLOW)
			)
		"喝咖啡":
			return (
				func (): 
					var block_duration = 0.2 * level
					var block_buff = BuffFactory.create_block_buff(block_duration)
					Utils.player.buff_manager.add_buff(block_buff, Utils.player)
					Utils.show_string_label_c("格挡准备就绪", Utils.player, Color.CYAN)
					print("喝咖啡技能触发，格挡持续时间: " + str(block_duration) + "秒")
			)	
		"火球术":
			return (
				func (): 
					# 获取鼠标位置作为目标
					var mouse_pos = Utils.player.get_global_mouse_position()
					var direction = Utils.player.global_position.direction_to(mouse_pos)
					
					# 创建火球
					var fireball_scene = preload("res://scenes/vfx/fire_ball(火球)/fireball.tscn")
					var fireball = fireball_scene.instantiate()
					Utils.player.get_parent().add_child(fireball)
					
					# 设置火球参数
					fireball.damage = 20 * level + Utils.get_player_stats_value("max_mp")
					if Utils.player.buff_manager.has_buff("死神之书"):
						fireball.damage += Utils.get_player_stats_value("max_mp")
					fireball.speed = 500.0 + Utils.get_player_stats_value("move_speed")
					fireball.lifetime = 10.0
					fireball.explosion_radius = 150.0
					
					# 初始化火球
					fireball.init(Utils.player.global_position, direction)
					
					Utils.show_string_label_c("火球术！", Utils.player, Color.ORANGE)
					print("火球术触发，伤害: " + str(fireball.damage))
			)	
		"燃烧吧":
			return (
				func (): 
				# 检查是否已经有燃烧buff
				if Utils.player.buff_manager.has_buff("燃烧"):
					# 如果已经有燃烧buff，则移除它
					Utils.player.buff_manager.remove_buff("燃烧")
					Utils.show_string_label_c("燃烧停止", Utils.player, Color.YELLOW)
					print("燃烧停止")
					
					# 停止燃烧特效
					var burn_effect = Utils.player.get_node_or_null("BurnEffect")
					if burn_effect:
						burn_effect.stop_burning()
				else:
					# 创建燃烧buff
					var burn_damage = 0.5 * level
					var attack_speed_bonus = 50 * level
					var burn_buff = BuffFactory.create_burning_buff(burn_damage, attack_speed_bonus)
					Utils.player.buff_manager.add_buff(burn_buff, Utils.player)
					
					Utils.show_string_label_c("燃烧开始！", Utils.player, Color.ORANGE)
					print("燃烧开始，伤害: " + str(burn_damage) + "，攻速加成: " + str(attack_speed_bonus))
					
					# 启动燃烧特效
					var burn_effect = Utils.player.get_node_or_null("BurnEffect")
					if burn_effect:
						burn_effect.start_burning()
			)
		"水之庇护":
			return (
				func (): 
					# 水之庇护是被动技能，直接应用属性加成
					var move_speed_bonus = 10 * level
					var attack_speed_bonus = 10 * level
					
					# 先移除之前的加成（如果有的话）
					# 这里我们假设每次调用都是重新计算，所以直接应用新值
					Utils.set_player_stats_value("additional_move_speed", move_speed_bonus)
					Utils.set_player_stats_value("additional_attack_speed", attack_speed_bonus)
					# 启动水之庇护光环特效
					var authority_aura = Utils.player.authority_aura
					if authority_aura:
						authority_aura.start_aura()
						authority_aura.set_aura_intensity(level)
					
					Utils.show_string_label_c("水之庇护激活！", Utils.player, Color.CYAN)
					print("水之庇护激活，移速加成: " + str(move_speed_bonus) + "，攻速加成: " + str(attack_speed_bonus))
			)
		"隐身":
			return (
				func (): 
					# 隐身技能：n秒内敌人不会主动攻击，下一次攻击额外造成1.0 + 0.1 * n倍伤害
					var stealth_duration = level  # n秒隐身时间
					var damage_multiplier = 1.0 + 0.1 * level  # 伤害倍数
					
					# 创建隐身buff（不包含伤害倍数，伤害倍数单独处理）
					var stealth_buff = BuffFactory.create_stealth_buff(stealth_duration)
					Utils.player.buff_manager.add_buff(stealth_buff, Utils.player)

					# 单独设置伤害倍数（在攻击后移除）
					Utils.set_player_stats_value("stealth_damage_multiplier", damage_multiplier)
					
					# 设置玩家半透明效果
					Utils.player.visuals.modulate.a = 0.5
					
					# 通知所有敌人玩家进入隐身状态
					EventBus.push_event("player_stealth_start", [])
					
					Utils.show_string_label_c("隐身开始！", Utils.player, Color.PURPLE)
					print("隐身技能触发，持续时间: " + str(stealth_duration) + "秒，伤害倍数: " + str(damage_multiplier))
			)
	return func(): pass

## 更新技能信息
func update_skill_info(skill_pandora: PandoraEntity, skill_name, level):
	if skill_name == '攻击提升':
		var base_mp_cost = 1
		var actual_mp_cost = base_mp_cost * level
		skill_pandora.set_string("skill_info", "消耗%s蓝量，10秒内提升%s%%攻击力" % [actual_mp_cost, 10 * level])
	elif skill_name == '大肉':
		skill_pandora.set_string("skill_info", "增加%s点生命值" % [10 * level])
	elif skill_name == '冲刺':
		skill_pandora.set_string("skill_info", "冲刺一段距离")
	elif skill_name == '魔法之书':
		skill_pandora.set_string("skill_info", "增加%s点魔法值" % [10 * level])
	elif skill_name == '灼烧':
		skill_pandora.set_string("skill_info", "攻击时对敌人造成每秒%s点烧伤伤害，持续3秒，可叠加5层" % [level * 0.5])
	elif skill_name == '毒液喷射':
		skill_pandora.set_string("skill_info", "对自身造成%s秒中毒效果，每秒造成%s点伤害" % [10, 5 * level])
	elif skill_name == '火焰冲击':
		skill_pandora.set_string("skill_info", "对自身造成%s秒烧伤效果，每秒造成%s点伤害" % [8, 8 * level])
	elif skill_name == '电击术':
		skill_pandora.set_string("skill_info", "对自身造成%s秒电击效果，每秒造成%s点伤害" % [12, 3 * level])
	elif skill_name == '冰冻术':
		skill_pandora.set_string("skill_info", "对自身造成%s秒冰冻效果，移动速度降低" % [5])
	elif skill_name == '眩晕术':
		skill_pandora.set_string("skill_info", "对自身造成%s秒眩晕效果，无法移动" % [3])
	elif skill_name == '治疗术':
		var base_mp_cost = 2
		var actual_mp_cost = base_mp_cost * level
		skill_pandora.set_string("skill_info", "消耗%s蓝量，恢复%s点生命值 + （%s最大魔法值）" % [actual_mp_cost, 5 * level, Utils.get_player_stats_value("max_mp")])
	elif skill_name == '喝咖啡':
		skill_pandora.set_string("skill_info", "消耗0蓝量，%s秒内可以格挡敌人的下一次攻击" % [0.2 * level])
	elif skill_name == '火球术':
		var base_mp_cost = 2
		var actual_mp_cost = base_mp_cost * level
		skill_pandora.set_string("skill_info", "消耗%s蓝量，对敌人造成%s点伤害 + 最大mp值 * 1" % [actual_mp_cost, 20 * level])
	elif skill_name == '燃烧吧':
		var base_mp_cost = 1
		var actual_mp_cost = base_mp_cost * level
		skill_pandora.set_string("skill_info", "消耗%s蓝量，切换燃烧状态，每秒扣%s点血，攻速加%s点" % [actual_mp_cost, 0.5 * level, 50 * level])
	elif skill_name == '水之庇护':
		skill_pandora.set_string("skill_info", "被动技能：增加%s%%移速和%s%%攻速" % [10 * level, 10 * level])
	elif skill_name == '隐身':
		var base_mp_cost = 1
		var actual_mp_cost = base_mp_cost * level
		skill_pandora.set_string("skill_info", "消耗%s蓝量，%s秒内敌人不会主动攻击，下一次攻击额外造成%s倍伤害" % [actual_mp_cost, level, 1.0 + 0.1 * level])

## 复制的时候，去除子节点
func remove_script(ghost):
	for child in ghost.get_children():
		Utils.remove_script(child)

## 改变剑的颜色
func _change_sword_color(color: Color, duration: float) -> void:
	# 查找玩家的剑
	var sword = Utils.player.weapon_root.get_child(0)
	
	# 创建颜色变化动画
	var tween = sword.create_tween()
	tween.tween_property(sword, "modulate", color, 0.5)
			
	# 改变剑轨迹的颜色
	var sword_line = sword.get_node_or_null("sword_line")
	if sword_line and sword_line.has_method("change_trail_color"):
		sword_line.change_trail_color(color, duration)
			
	# 持续时间后恢复原色
	await get_tree().create_timer(duration).timeout
	tween = sword.create_tween()
	tween.tween_property(sword, "modulate", Color.WHITE, 0.5)
